import 'dart:async';
import 'dart:io';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:hc_connectivity/hc_connectivity.dart';
import 'package:hc_connectivity/hc_method_channel_connectivity.dart';
import 'package:hc_connectivity/wifi_network.dart';

// Sets a platform override for desktop to avoid exceptions. See
// https://flutter.dev/desktop#target-platform-override for more info.
void _enablePlatformOverrideForDesktop() {
  if (!kIsWeb && (Platform.isWindows || Platform.isLinux)) {
    debugDefaultTargetPlatformOverride = TargetPlatform.fuchsia;
  }
}

void main() {
  _enablePlatformOverrideForDesktop();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, @required this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String _connectionStatus = 'Unknown';
  final HcConnectivity _connectivity = HcConnectivity();
  StreamSubscription<List<WifiNetwork>> _connectivitySubscription;

  @override
  void initState() {
    super.initState();

    initConnectivity();
    _connectivitySubscription =
        _connectivity.onConnectivityChanged.listen(_updateConnectionStatus);
  }

  @override
  void dispose() {
    _connectivitySubscription.cancel();
    super.dispose();
  }

  @override
  reassemble() {
    super.reassemble();
    initConnectivity();
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initConnectivity() async {
    await _connectivity.setEnabled(true);
    print(await _connectivity.getWifiIP());
    print(await _connectivity.getWifiName());
    print(await _connectivity.isEnabled());
    print(await _connectivity.isConnected());

    // final res = await _connectivity.registerWifiNetwork(
    //   'HUAWEI-MPJRB6',
    //   password: '12345678',
    //   security: NetworkSecurity.WPA,
    // );

    // await _connectivity.connect('MERCURY_8A38',
    //     password: '137375803171+', security: NetworkSecurity.WPA);
    var e = await _connectivity.openWifiNetwork();
    print('--------');
    // print(e);
    print('--------');

    List<WifiNetwork> result = <WifiNetwork>[];
    // Platform messages may fail, so we use a try/catch PlatformException.
    try {
      result = await _connectivity.checkConnectivity();
      print(result.length);
    } on PlatformException catch (e) {
      print(e.toString());
    }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) {
      return Future.value(null);
    }

    return _updateConnectionStatus(result);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text('Connectivity example app'),
        ),
        body: Container(
          child: Column(
            children: [
              Center(child: Text('wifi: $_connectionStatus')),
              FlatButton(
                onPressed: () => {initConnectivity()},
                child: Text('scan'),
                textColor: Colors.black,
              ),
              FlatButton(
                onPressed: () async {
                  try {
                    final name = 'HUAWEI-MPJRB6';
                    final pwd = '12345678';
                    final res = await _connectivity.registerWifiNetwork(
                      name,
                      password: pwd,
                      security: NetworkSecurity.WPA,
                    );

                    print('res $res');
                  } catch (e) {
                    print(e);
                  }
                },
                child: Text('判断连接'),
                textColor: Colors.black,
              )
            ],
          ),
        ));
  }

  Future<void> _updateConnectionStatus(List<WifiNetwork> result) async {
    print('==================');
    print(result.length);
    setState(() => _connectionStatus = result.map((e) => e.ssid).toString());
  }
}
